package com.ruoyi.edh.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.edh.domain.EdhBill;
import com.ruoyi.edh.domain.EdhProfit;
import com.ruoyi.edh.domain.dto.EdhBatchShipDto;
import com.ruoyi.edh.domain.dto.EdhOrderGoodsDto;
import com.ruoyi.edh.domain.dto.EdhOrderListDto;
import com.ruoyi.edh.domain.vo.*;
import com.ruoyi.edh.mapper.EdhBillMapper;
import com.ruoyi.edh.mapper.EdhProfitMapper;
import com.ruoyi.edh.mapper.EdhReturnGoodsMapper;
import com.ruoyi.edh.service.IEdhMicroshopService;
import org.apache.ibatis.annotations.Lang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.ruoyi.edh.mapper.EdhOrderMapper;
import com.ruoyi.edh.domain.EdhOrder;
import com.ruoyi.edh.service.IEdhOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 易订购-订单Service业务层处理
 *
 * @author xxx
 * @date 2020-09-03
 */
@Service
public class EdhOrderServiceImpl implements IEdhOrderService {
    @Autowired
    private EdhOrderMapper edhOrderMapper;

    @Autowired
    private EdhReturnGoodsMapper returnGoodsMapper;

    @Autowired
    private EdhBillMapper billMapper;

    @Autowired
    private EdhProfitMapper profitMapper;

    /**
     * 查询易订购-订单
     *
     * @param id 易订购-订单ID
     * @return 易订购-订单
     */
    @Override
    public EdhOrder selectEdhOrderById(Long id) {
        return edhOrderMapper.selectEdhOrderById(id);
    }

    /**
     * 查询易订购-订单列表
     *
     * @param edhOrder 易订购-订单
     * @return 易订购-订单
     */
    @Override
    public List<EdhSummaryOrderListVo> selectEdhOrderList(EdhOrderListDto edhOrder) {
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserConstants.SUPPLIER_USER)) {
            edhOrder.setSupplierId(SecurityUtils.getUserId());
        }
        return edhOrderMapper.queryEdhOrderList(edhOrder);
    }

    @Override
    public List<EdhSummaryOrderExcleListVo> selectEdhOrderExcelList(EdhOrderListDto edhOrder) {
        return edhOrderMapper.selectEdhOrderExcelList(edhOrder);
    }

    /**
     * 新增易订购-订单
     *
     * @param edhOrder 易订购-订单
     * @return 结果
     */
    @Override
    public int insertEdhOrder(EdhOrder edhOrder) {
        return edhOrderMapper.insertEdhOrder(edhOrder);
    }

    /**
     * 修改易订购-订单
     *
     * @param edhOrder 易订购-订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateEdhOrder(EdhOrder edhOrder) {
        EdhOrder order = edhOrderMapper.selectEdhOrderById(edhOrder.getId());
        // 如果是确认收货的话   加账单 加收益
        if (edhOrder.getOrderStatus().equals("3") && order.getOrderStatus().equals("2")) {
            insertProfitAndBill(edhOrder.getId());
        }
        // 如果是发货的话 增加发货时间
        if ("1".equals(order.getOrderStatus()) && "2".equals(edhOrder.getOrderStatus()) && "1".equals(edhOrder.getShipStatus())) {
            edhOrder.setShipTime(DateUtils.getNowDate());
        }
        // 如果是确认付款的话  增加付款时间
        if ("0".equals(order.getOrderStatus()) && "1".equals(edhOrder.getOrderStatus())) {
            edhOrder.setPaymentTime(DateUtils.getNowDate());
        }

        Boolean status = true;
        edhOrder.setUpdateTime(DateUtils.getNowDate());
        int update = edhOrderMapper.updateEdhOrder(edhOrder);
        if (update < 0) {
            status = false;
        }
        Integer addLog = edhOrderMapper.addOrderLog(SecurityUtils.getUserId(), edhOrder.getId(), "状态修改");
        if (addLog < 0) {
            status = false;
        }
        return status ? 1 : 0;
    }

    /**
     * @param orderid
     * @Author: 周爱鸿
     * @Description: 确认收货  增加收益  增加账单
     * @CreateDate: 2020/11/4 11:44
     */
    @Override
    public int insertProfitAndBill(Long orderid) {

        // 根据orderids生成团长的账单]
        EdhBill leaderBills = edhOrderMapper.generatingLeaderBills(orderid);
        // 根据orderids生成团长的团长的账单
        EdhBill bossBills = edhOrderMapper.generatingBossBills(orderid);

        // 增加上级的收益记录
        if (StringUtils.isNotNull(leaderBills) && StringUtils.isNotEmpty(leaderBills.getPrice())) {
            billMapper.insertEdhBill(leaderBills);
            //查看团长是否有收益表   没有的话新建
            EdhProfit edhProfit = profitMapper.selectProfitByUserId(leaderBills.getCreateBy());
            if (StringUtils.isNull(edhProfit)) {
                BigDecimal price = new BigDecimal(leaderBills.getPrice());
                edhProfit = new EdhProfit();
                edhProfit.setTodayBenefits(price);
                edhProfit.setMyBenefits(price);
                edhProfit.setAllBenefits(price);
                edhProfit.setNotWithdrawn(price);
                edhProfit.setCreateBy(leaderBills.getCreateBy() + "");
                edhProfit.setCreateTime(DateUtils.getNowDate());
                edhProfit.setRemake("系统创建");
                profitMapper.insertEdhProfit(edhProfit);
            } else {
                profitMapper.growthRateByUserId(leaderBills.getCreateBy(), leaderBills.getPrice(), 1);
            }
        }
        // 增加上级的上级的收益记录
        if (StringUtils.isNotNull(bossBills) && StringUtils.isNotNull(leaderBills)) {
            billMapper.insertEdhBill(bossBills);
            //查看团长是否有收益表   没有的话新建
            EdhProfit edhProfit = profitMapper.selectProfitByUserId(bossBills.getCreateBy());
            if (StringUtils.isNull(edhProfit)) {
                BigDecimal price = new BigDecimal(bossBills.getPrice());
                edhProfit = new EdhProfit();
                edhProfit.setTodayBenefits(price);
                edhProfit.setTeamBenefits(price);
                edhProfit.setAllBenefits(price);
                edhProfit.setNotWithdrawn(price);
                edhProfit.setCreateBy(bossBills.getCreateBy() + "");
                edhProfit.setCreateTime(DateUtils.getNowDate());
                edhProfit.setRemake("系统创建");
                profitMapper.insertEdhProfit(edhProfit);
            } else {
                profitMapper.growthRateByUserId(bossBills.getCreateBy(), bossBills.getPrice(), 2);
            }
        }


        return 1;
    }

    /**
     * 批量删除易订购-订单
     *
     * @param ids 需要删除的易订购-订单ID
     * @return 结果
     */
    @Override
    public int deleteEdhOrderByIds(String[] ids) {
        return edhOrderMapper.deleteEdhOrderByIds(ids);
    }

    /**
     * 删除易订购-订单信息
     *
     * @param id 易订购-订单ID
     * @return 结果
     */
    @Override
    public int deleteEdhOrderById(Long id) {
        return edhOrderMapper.deleteEdhOrderById(id);
    }

    /**
     * 查询我的订单
     *
     * @param orderStatus
     * @return
     */
    @Override
    public List<EdhMyOrderVo> selectEdhMyOrder(String orderStatus, String returnStatus) {
        return edhOrderMapper.selectEdhMyOrder(SecurityUtils.getUserId().toString(), orderStatus, returnStatus);
    }

    /**
     * 查询微店订单
     *
     * @param edhOrder
     * @return 订单列表
     */
    @Override
    public List<EdhMyOrderVo> selectMicroshopList(EdhOrderListDto edhOrder) {
        return edhOrderMapper.selectMicroshopList(edhOrder);
    }

    /**
     * @param id
     * @description: 根据订单id查询当前订单详情
     * @return:
     * @author: 梁东宸
     * @time: 2020/9/5 4:12 下午
     */
    @Override
    public EdhDetailsOrderVo selectDetailsOrder(String id) {
        return edhOrderMapper.selectDetailsOrder(id);
    }

    /**
     * 获取订单销售情况
     */
    @Override
    public Map<String, Object> getOrderFulfillment() {
        Long userId = null;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!user.getUserType().equals(UserConstants.SYSTEM_USER)) {
            userId = user.getUserId();
        }
        return edhOrderMapper.getOrderFulfillment(userId);
    }

    /**
     * 首页待处理事务数据
     */
    @Override
    public Map<String, Object> pendingTransaction() {
        Long userId = null;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!user.getUserType().equals(UserConstants.SYSTEM_USER)) {
            userId = user.getUserId();
        }
        return edhOrderMapper.pendingTransaction(userId);
    }

    /**
     * 首页订单总数统计图数据
     */
    @Override
    public Map<String, Object> totalOrdersStatistics(Integer type, String time) {

        Map<String, Object> result = new HashMap<String, Object>(16);

        List<String> orderNumbers;
        List<Map<String, Object>> list;
        Iterator<Map<String, Object>> iterator;
        Map<String, Object> map;

        Long userId = null;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!user.getUserType().equals(UserConstants.SYSTEM_USER)) {
            userId = user.getUserId();
        }


        if (null == type) {
            type = 2;
        }
        switch (type) {
            // 查询今日
            case 1:
                String[] days = DateUtils.day;
                orderNumbers = new LinkedList<String>();
                list = edhOrderMapper.totalOrdersToday(userId);
                iterator = list.iterator();
                map = new HashMap<String, Object>(16);
                if (iterator.hasNext()) {
                    map = iterator.next();
                }
                for (int i = 0; i < days.length; i++) {
                    if (StringUtils.isNotNull(map)) {
                        String createTime = (String) map.get("createTime");
                        if (days[i].equals(createTime)) {
                            orderNumbers.add(map.get("orderNumber") + "");
                            if (iterator.hasNext()) {
                                map = iterator.next();
                            }
                        } else {
                            orderNumbers.add("0");
                        }
                    }
                }
                result.put("xAxisData", days);
                result.put("yAxisData", orderNumbers.toArray());
                break;
            // 查询本月
            case 3:
                String[] months = DateUtils.month;
                orderNumbers = new LinkedList<String>();
                list = edhOrderMapper.totalOrdersThisMonth(userId);
                iterator = list.iterator();
                map = new HashMap<String, Object>(16);
                if (iterator.hasNext()) {
                    map = iterator.next();
                }
                for (int i = 0; i < months.length; i++) {
                    if (StringUtils.isNotNull(map)) {
                        String createTime = map.get("createTime") + "";
                        if (months[i].equals(createTime)) {
                            orderNumbers.add(map.get("orderNumber") + "");
                            if (iterator.hasNext()) {
                                map = iterator.next();
                            }
                        } else {
                            orderNumbers.add("0");
                        }
                    }
                }
                result.put("xAxisData", months);
                result.put("yAxisData", orderNumbers.toArray());
                break;
            // 查询本周
            default:
                String[] weeks = DateUtils.week;
                orderNumbers = new LinkedList<String>();
                list = edhOrderMapper.totalOrdersThisWeek(userId);
                iterator = list.iterator();
                map = new HashMap<String, Object>(16);
                if (iterator.hasNext()) {
                    map = iterator.next();
                }
                for (int i = 0; i < weeks.length; i++) {
                    if (StringUtils.isNotNull(map)) {
                        String createTime = (String) map.get("createTime");
                        if (weeks[i].equals(createTime)) {
                            orderNumbers.add(map.get("orderNumber") + "");
                            if (iterator.hasNext()) {
                                map = iterator.next();
                            }
                        } else {
                            orderNumbers.add("0");
                        }
                    }
                }
                result.put("xAxisData", weeks);
                result.put("yAxisData", orderNumbers.toArray());
                break;
        }

        return result;
    }

    /**
     * 首页订单销售额统计图数据
     *
     * @param type
     * @param time
     */
    @Override
    public Map<String, Object> orderSalesStatistics(Integer type, String time) {
        Map<String, Object> result = new HashMap<String, Object>(16);

        List<String> orderSales;
        List<Map<String, Object>> list;
        Iterator<Map<String, Object>> iterator;
        Map<String, Object> map;

        Long userId = null;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!user.getUserType().equals(UserConstants.SYSTEM_USER)) {
            userId = user.getUserId();
        }

        if (null == type) {
            type = 2;
        }
        switch (type) {
            // 查询今日
            case 1:
                String[] days = DateUtils.day;
                orderSales = new LinkedList<String>();
                list = edhOrderMapper.totalOrdersSaleToday(userId);
                iterator = list.iterator();
                map = new HashMap<String, Object>(16);
                if (iterator.hasNext()) {
                    map = iterator.next();
                }
                for (int i = 0; i < days.length; i++) {
                    if (StringUtils.isNotNull(map)) {
                        String createTime = (String) map.get("createTime");
                        if (days[i].equals(createTime)) {
                            orderSales.add(map.get("orderSale") + "");
                            if (iterator.hasNext()) {
                                map = iterator.next();
                            }
                        } else {
                            orderSales.add("0");
                        }
                    }
                }
                result.put("xAxisData", days);
                result.put("yAxisData", orderSales.toArray());
                break;
            // 查询本月
            case 3:
                String[] months = DateUtils.month;
                orderSales = new LinkedList<String>();
                list = edhOrderMapper.totalOrdersSaleThisMonth(userId);
                iterator = list.iterator();
                map = new HashMap<String, Object>(16);
                if (iterator.hasNext()) {
                    map = iterator.next();
                }
                for (int i = 0; i < months.length; i++) {
                    if (StringUtils.isNotNull(map)) {
                        String createTime = map.get("createTime") + "";
                        if (months[i].equals(createTime)) {
                            orderSales.add(map.get("orderSale") + "");
                            if (iterator.hasNext()) {
                                map = iterator.next();
                            }
                        } else {
                            orderSales.add("0");
                        }
                    }
                }
                result.put("xAxisData", months);
                result.put("yAxisData", orderSales.toArray());
                break;
            // 查询本周
            default:
                String[] weeks = DateUtils.week;
                orderSales = new LinkedList<String>();
                list = edhOrderMapper.totalOrdersSaleThisWeek(userId);
                iterator = list.iterator();
                map = new HashMap<String, Object>(16);
                if (iterator.hasNext()) {
                    map = iterator.next();
                }
                for (int i = 0; i < weeks.length; i++) {
                    if (StringUtils.isNotNull(map)) {
                        String createTime = (String) map.get("createTime");
                        if (weeks[i].equals(createTime)) {
                            orderSales.add(map.get("orderSale") + "");
                            if (iterator.hasNext()) {
                                map = iterator.next();
                            }
                        } else {
                            orderSales.add("0");
                        }
                    }
                }
                result.put("xAxisData", weeks);
                result.put("yAxisData", orderSales.toArray());
                break;
        }

        return result;
    }

    /**
     * 首页订单总数对比数据
     */
    @Override
    public Map<String, Object> totalOrderComparison() {

        Long userId = null;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!user.getUserType().equals(UserConstants.SYSTEM_USER)) {
            userId = user.getUserId();
        }

        return edhOrderMapper.totalOrderComparison(userId);
    }

    /**
     * 首页订单销售额对比数据
     */
    @Override
    public Map<String, Object> totalOrderSalesComparison() {

        Long userId = null;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!user.getUserType().equals(UserConstants.SYSTEM_USER)) {
            userId = user.getUserId();
        }

        return edhOrderMapper.totalOrderSalesComparison(userId);
    }

    /**
     * @param edhBatchShip
     * @description: 批量发货
     * @return: Integer
     * @author: 梁东宸
     * @time: 2020/9/15 3:06 下午
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer batchShip(List<EdhOrder> edhBatchShip) {
        Boolean status = true;
        edhBatchShip.forEach(ship -> {
            if (0 > edhOrderMapper.batchShip(ship)) {
                throw new CustomException("修改失败");
            }
        });
        for (EdhOrder edhOrder : edhBatchShip) {
            Integer addLog = edhOrderMapper.addOrderLog(SecurityUtils.getUserId(), edhOrder.getId(), "批量发货统一操作");
            if (addLog < 0) {
                status = false;
            }
        }
        return status == true ? 1 : 0;
    }

    /**
     * @param id
     * @description: 根据id查询订单详情
     * @return: EdhOrderDetailsVo
     * @author: 梁东宸
     * @time: 2020/9/15 8:37 下午
     */
    @Override
    public EdhOrderDetailsVo selectOrderDetailsById(String id) {
        return edhOrderMapper.selectOrderDetailsById(id);
    }

    /**
     * @description:
     * @paramid,remarks 订单id和订单备注
     * @return:
     * @author: 梁东宸
     * @time: 2020/9/16 4:03 下午
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addOrderLog(Long id, String remarks, String type) {
        Boolean cancel = true;
        if ("1".equals(type)) {
            EdhOrder edhOrder = new EdhOrder();
            edhOrder.setId(id);
            edhOrder.setOrderStatus("4");
            edhOrder.setCancelTime(new Date());
            int i = edhOrderMapper.updateEdhOrder(edhOrder);
            if (i < 1) {
                cancel = false;
            }
        }
        Integer integer = edhOrderMapper.addOrderLog(SecurityUtils.getUserId(), id, remarks);
        if (integer < 1) {
            cancel = false;
        }
        return cancel == false ? 0 : 1;
    }

    @Override
    public List<EdhOrderDetailsVo> selectNotShipOrder(EdhOrder edhOrder) {
        return edhOrderMapper.selectNotShipOrder(edhOrder);
    }

    /**
     * @param ids
     * @description: printShip
     * @return: Integer
     * @author: 梁东宸
     * @time: 2020/9/17 1:44 下午
     */
    @Override
    public Integer printShip(Long[] ids) {
        return edhOrderMapper.printShip(ids);
    }

    /**
     * @param edhOrder
     * @description: 被调用时异步修改状态
     * @return: Integer
     * @author: 梁东宸
     * @time: 2020/9/18 9:38 上午
     */
    @Override
    @Async
    public Integer updateOrderStatus(EdhOrder edhOrder) {
        return edhOrderMapper.updateEdhOrder(edhOrder);
    }

    /**
     * @param outTradeNo 主订单号
     * @description: 主订单号
     * @return: Integer
     * @author: 梁东宸
     * @time: 2020/9/29 7:38 下午
     */
    @Override
    public Integer updateOrderStatusFailure(String outTradeNo) {
        return edhOrderMapper.updateOrderStatusFailure(outTradeNo);
    }

    @Override
    public int cancelAftermarket(Long orderId) {
        EdhOrder order = new EdhOrder();
        order.setId(orderId);
        order.setReturnStatus("2");
        order.setOrderStatus("3");
        returnGoodsMapper.deleteEdhReturnGoodsByOrderId(orderId);
        return edhOrderMapper.updateOrderStatus(order);
    }
}
